Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

423
Visualizações
What is the different between the ref={callback} and the ref = "myInput" in react?

as the link https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

It then only gives an example of using the component immediately. I'm trying to find out how i would use this function to access the component immediately, and save the component for future use, as it says we are able to do.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The difference is using ref={callback} react passes the responsibility of managing the reference storage back to you. When you use ref="sometext", under the covers react has to create a refs property on your class and then add all the ref="sometext" statements to it.

While its nice to have a simple this.refs.sometext access to components its difficult and error prone on the react side to clean up this refs property when the component is destroyed. It's much easier for react to pass you the component and let you handle storing it or not.

According to the react docs

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

This is actually a pretty slick idea, by passing null on unmount and calling your callback again you automatically clean up references.

To actually use it all you have to do is access it from any function like so:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in this.textInput.
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

The callback you set on ref will receive the component as the first parameter, the 'this' word will be the current class 'CustomTextInput' in this example. Setting this.textInput in your callback will make textInput available to all other functions like focus()

Concrete Example

Tweet from Dan Abermov showing a case where ref callbacks work better

enter image description here

Update

Per Facebook Docs using strings for refs is consider legacy and they "recommend using either the callback pattern or the createRef API instead."

over 4 years ago · Santiago Trujillo Relatório

0

When you assign a ref={callback} like <input type="text" ref={(input) => {this.textInput = input}}/> what basically you are doing is saving the ref with the name textInput for future use. So instead of using ref="myInput" and then using this.refs.myInput we can use the call back bethod and then access the component later like this.textInput.

Here is a demo for the same, whereby we are accessing the input value using ref on button click

class App extends React.Component {
  constructor(){
    super();
  }
  handleClick = () => {
    console.log(this.textInput.value);
  }
  render() {
    return (
      <div>
        <input type="text" ref={(input) => {this.textInput = input}}/>
        <button type="button" onClick={this.handleClick}>Click</button>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react-dom.min.js"></script>
<div id="app"></div>

over 4 years ago · Santiago Trujillo Relatório

0

With React 16.3, you can use React.createRef() API instead:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  render() {
    return <div ref={this.myRef} />;
  }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda